package com.bjpowernode.springsecurity03.service.impl;

import com.bjpowernode.springsecurity03.domain.SysUser;
import com.bjpowernode.springsecurity03.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AppUserServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserMapper.findByUsername(username);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<String> authorities = sysUserMapper.findPermissionsByUserId(sysUser.getUserId());

        List<SimpleGrantedAuthority> permissions = new ArrayList<>();
        for (String a : authorities) {
            permissions.add(new SimpleGrantedAuthority(a));
        }

        sysUser.setPermissions(permissions);

        return sysUser;
    }
}

